package com.example.rabbitmq.limit;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @author： ygl
 * @date： 2019/06/15
 * @Description：
 */
public class MyConsumer {

    public static void main(String[] args) throws Exception {

        // 1.创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        // 2.通过链接工厂创建链接
        Connection connection = connectionFactory.newConnection();
        // 3.通过connection创建channel信道
        Channel channel = connection.createChannel();

        String exchangeName = "test_qos_exchange";
        String routingKey = "qos.#";
        String queueName = "test_qos_queue";
        String exchangeType = "topic";

        // 声明交换机
        channel.exchangeDeclare(exchangeName,exchangeType,true,false,false,null);
        // 声明队列
        channel.queueDeclare(queueName,false,false,false,null);
        // 建立绑定关系
        channel.queueBind(queueName,exchangeName,routingKey);

        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                String msg = new String(body,"utf-8");
                System.out.println("默认的消费者消费消息-----："+msg);
                // 消息处理完毕
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };

        // 限流方式 一：autoAck 为fasle
        channel.basicQos(0,1,false);
        channel.basicConsume(queueName, false, defaultConsumer);
    }
}
